from flask import request
from flask_socketio import SocketIO


class MysqlConfig:
    """mysql连接配置"""
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:12345678@localhost/llm_studio'
    SQLALCHEMY_TRACK_MODIFICATIONS = False


class SocketConfig:
    """socket连接配置"""

    def __init__(self, app):
        self.socketio = SocketIO(app,async_mode='eventlet', cors_allowed_origins="*")
        self.clients = set()  # 存储连接的客户端ID
        # 注册事件处理方法
        self.register_events()

    def register_events(self):
        @self.socketio.on('connect')
        def handle_connect():
            """处理客户端连接事件"""
            print(f'客户端已连接: {request.sid}')
            self.clients.add(request.sid)
            # 向客户端发送连接成功消息
            self.socketio.emit('system_message', {'message': '你已成功连接服务器'})

        @self.socketio.on('disconnect')
        def handle_disconnect():
            """处理客户端断开连接事件"""
            print(f'客户端已断开连接: {request.sid}')
            self.clients.discard(request.sid)

        @self.socketio.on('client_message')
        def handle_client_message(data):
            """处理客户端发送的消息"""
            print(f'收到来自{request.sid}的消息: {data}')
            # 广播消息给所有客户端(除了发送者)
            self.socketio.emit('server_message', {
                'sender': request.sid,
                'message': data['message']
            }, skip_sid=request.sid)

    def send_message(self, message):
        """从API接口发送消息给所有客户端"""
        if self.clients:
            self.socketio.emit('server_message', {
                'sender': 'system',
                'message': message
            })
            return True
        return False

    def send(self, message):
        """从API接口发送消息给所有客户端"""
        if self.clients:
            self.socketio.emit('monitoring_data', {
                'sender': 'system',
                'message': message
            })
            return True
        return False
